package utils.binary.impl;

import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import utils.binary.BytesSlices;

/**
 * @author Zhou Yifan
 */
public class BytesSliceArrayWrapper implements BytesSlices {

    private final BytesSlice slice;

    private BytesSliceArrayWrapper(BytesSlice slice) {
        this.slice = slice;
    }

    /**
     * 总的字节数；包含各个子数据片段之间间隔的头部字节
     *
     * @return int
     */
    @Override
    public int getTotalSize() {
        return slice.getSize();
    }

    /**
     * 包含的子片段的数量
     *
     * @return int
     */
    @Override
    public int getCount() {
        return 1;
    }

    /**
     * 返回一个子数据片段
     *
     * @param idx 子数据片段的编号；大于等于 0 ，小于总数 {@link #getCount()}
     * @return {@link BytesSlice}
     */
    @Override
    public BytesSlice getDataSlice(int idx) {
        if (idx != 0) {
            throw new IndexOutOfBoundsException(
                    "The specified idx is out of bound!"
            );
        }
        return slice;
    }

    @Contract(value = "null -> new", pure = true)
    public static @NotNull BytesSlices wrap(BytesSlice slice) {
        if (slice instanceof BytesSlices) {
            return (BytesSlices) slice;
        }
        return new BytesSliceArrayWrapper(slice);
    }
}
